from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from fastapi.templating import Jinja2Templates
from backend.models.models import init_db  # 修改为绝对导入
import os
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse

# 初始化数据库
init_db()

from backend.routers import login, records, admin  # 修改为绝对导入

app = FastAPI()

# 配置跨域（开发阶段常用）
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 获取当前文件目录
current_dir = os.path.dirname(os.path.abspath(__file__))

# 配置静态资源目录（使用绝对路径）
static_dir = os.path.join(current_dir, "static")
app.mount("/static", StaticFiles(directory=static_dir), name="static")

# 配置模板目录（使用绝对路径）
templates_dir = os.path.join(current_dir, "templates")
templates = Jinja2Templates(directory=templates_dir)

# 将 templates 对象传递给路由模块
from .routers import login, records, admin
login.templates = templates
records.templates = templates
admin.templates = templates

# 引入路由模块
app.include_router(login.router)
app.include_router(records.router)
app.include_router(admin.router)  # 添加admin路由

# 添加404错误处理
@app.exception_handler(404)
async def not_found_exception_handler(request: Request, exc):
    return templates.TemplateResponse("404.html", {"request": request}, status_code=404)

@app.get("/")
async def root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

if __name__ == "__main__":
    # 提供命令行初始化数据库的选项
    import sys
    if len(sys.argv) > 1 and sys.argv[1] == "--init-db":
        from models.models import init_db
        init_db()
        print("数据库初始化完成！")
    else:
        # 正常启动应用
        import uvicorn
        uvicorn.run("main:app", reload=True)